﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExamDemo.Data;
using ExamDemo.Models;
using ExamDemo.ViewModel;

namespace ExamDemo.Controllers
{
    public class MessagesController : Controller
    {
        public ExamDemoDb db = new ExamDemoDb();

        // GET: Messages
        public ActionResult Index()
        {
            if (Session["Username"] == null)
            {
                return RedirectToRoute(new { controller = "Users", action = "Login" });
            }

            var users = db.Users.ToList();
            var msgs = db.Messages.OrderByDescending(m => m.Id).ToList();
            var cmgs = db.Comments.ToList();

            var msgViewModeList = new List<MessageViewModel>();

            foreach (var msg in msgs)
            {
                var cmgViewModeList = new List<CommentViewModel>();

                var tmpComments = cmgs.Where(x => x.MsgId == msg.Id).ToList();

                foreach (var cmg in tmpComments)
                {
                    var fromUser = users.Where(x => x.Id == cmg.FromUserId).FirstOrDefault();
                    var m = msgs.Where(x => x.Id == cmg.MsgId).FirstOrDefault();
                    var toUser = users.Where(x => x.Id == m.FromUserId).FirstOrDefault();

                    cmgViewModeList.Add(new CommentViewModel
                    {
                        FromUsername = fromUser.Username,
                        ToUsername = toUser.Username,
                        Comment = cmg.Comment
                    });
                }

                msgViewModeList.Add(new MessageViewModel
                {
                    Id = msg.Id,
                    Content = msg.Content,
                    CommentViewModels = cmgViewModeList
                });
            }

            var vm = new SayViewModel
            {
                Username = (string)Session["Username"],
                MessageViewModel = msgViewModeList
            };
            return View(vm);
        }

        public ActionResult Say(string content)
        {
            dynamic result;
            if (content.Trim().Length > 0)
            {
                var message = db.Messages.Add(new Messages
                {
                    Content = content,
                    FromUserId = (int)Session["Id"]
                });

                db.SaveChanges();
                result = new
                {
                    code = 200,
                    content = content,
                    id = message.Id,
                    msg = "发表成功"
                };
            }
            else
            {
                result = new
                {
                    code = 340,
                    msg = "发表失败"
                };
            }
            return Json(result);
        }


        public ActionResult SayCom(string commentMsg, int msgId)
        {
            dynamic result;
            if (commentMsg.Trim().Length > 0)
            {
                var message = db.Comments.Add(new Comments
                {
                    Comment = commentMsg,
                    FromUserId = (int)Session["Id"],
                    MsgId = msgId
                });

                var userId = db.Messages.Find(msgId).FromUserId;
                var userName = db.Users.Find(userId).Username;

                db.SaveChanges();
                result = new
                {
                    code = 200,
                    content = commentMsg,
                    fromUserName = Session["Username"].ToString(),
                    toUserName = userName,
                    msgId,
                    msg = "发表成功"
                };
            }
            else
            {
                result = new
                {
                    code = 340,
                    msg = "评论失败"
                };
            }
            return Json(result);
        }




        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
